package pay

import (
	"context"
	"fmt"
	"github.com/smartwalle/alipay/v3"
	"log"
	"net/http"
	"strconv"
	"time"
)

func NewPayClient() *alipay.Client {
	APP_ID := "9021000128664148"

	//公钥
	PUBLIC_KEY := "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAos+7SWb2nkK057H09ax2AdYppnCfHXIrDU00nBea0hR/UTcBDlgHQET/vHwmSHaBEon9FaYRTih3Ltiaes/6OPltMd/8DA+F2C1+y4zvAkv4UuK17v22Xmr1ijjruwyvXih/FGSNxkybtUiv/BgtJAQdalR7q3anh8QFRdx6IeSECYpPJK9Xir3CqnG3Avx8l7NESMQLbcAtIScdpAH2kM8E2NKlB++iArgUpgQDagTfW54UcbcuDuj5iyADfIFdXZJoOpWWU+pBnn/rr0Jd/DAbEMbFwZxdOxmGMcj/0gr3Jz3vhXKyZ+ZNyKyy5XhXWkPOw68JucWk0ERLuebLoQIDAQAB"
	//私钥
	PRIVATE_KEY := "MIIEpAIBAAKCAQEAlT5l2d2sQoHZRyCgghtZn+mgwNnfehWdOHo4tTWQ0WqrE+cIJZyJmthxWBqfHR/2KdOp0yzYORnf4KxjP9PzKtFQpZTVaveVYLtNWLffIhQUZB+q9+jhT1A4mOlhMyp7F7s4nsZrAd0mPIG9Q40VnSMG2giG3XMAoQTC4piv59EWuLY3/we07zQKzA5EFOPd071ipgQkYji2Gic3r1GHT1Ek6KD1UK1VDC6a26VE6by+YTfKG+3KV2iaRD6uLcoLz2BUBJEp5oc2rIgpsqvMTws/KVuA/6XrRRF63+sPOaQOUo1uo16Q1wZKLdeDedHZm4iIuGFoA737j4G8LgAvvwIDAQABAoIBACcWwbxvV+fPdKYxgHizSyUcHtOD/QlP0e7x7BpiHj0LUCWVVEftmQjqeb1Ws6gAMAxCeO9rhnJmOYHyBMi57a2gRxwnQEKU+BXu2NJMzm9xjOmwdaoa37BTVY+PSLsK/FR539mOJIbHcnVUkcq4kBmpC+ldZF1p+pcx1Q1eamwvqk9U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Y, false)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	if err = client.LoadAliPayPublicKey(PUBLIC_KEY); err != nil {
		fmt.Println(err)
		return nil
	}
	return client
}

func Pay(orderSnc string, price string) string {
	client := NewPayClient()
	var p = alipay.TradeWapPay{}
	p.NotifyURL = "https://915br527pq19.vicp.fun/order/callback" //设置支付宝异步通知的回调URL，当支付状态发生变化时，支付宝会向该URL发送通知。
	p.ReturnURL = "http://www.baidu.com"                         //设置支付宝同步通知的回调URL，支付完成后用户将跳转回该URL
	p.Subject = "支付"                                             //标题
	p.OutTradeNo = "2088721013986740"                            //传递一个唯一单号
	p.TotalAmount = "1.00"                                       //金额
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"                     //产品代码
	currentTime := time.Now()
	unixTimestamp := currentTime.Unix()
	p.TimeoutExpress = strconv.FormatInt(unixTimestamp, 10) //设置超时时间，即订单有效期，以Unix时间戳形式表示。
	p.Body = "描述"                                           //设置订单描述信息。
	var str, err = client.TradeWapPay(p)
	if err != nil {
		fmt.Println(err)
	}
	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	fmt.Println(str.String())
	return str.String()
}

func Notify(writer http.ResponseWriter, request *http.Request) {
	client := NewPayClient()
	request.ParseForm()
	var notification, err = client.DecodeNotification(request.Form)
	if err != nil {
		log.Println("解析异步通知发生错误", err)
		return
	}

	log.Println("解析异步通知成功:", notification.NotifyId)

	// 示例一：使用自定义请求进行查询
	var p = alipay.NewPayload("alipay.trade.query")
	p.AddBizField("out_trade_no", notification.OutTradeNo)

	var rsp *alipay.TradeQueryRsp
	if err = client.Request(context.Background(), p, &rsp); err != nil {
		log.Printf("异步通知验证订单 %s 信息发生错误: %s \n", notification.OutTradeNo, err.Error())
		return
	}
	if rsp.IsFailure() {
		log.Printf("异步通知验证订单 %s 信息发生错误: %s-%s \n", notification.OutTradeNo, rsp.Msg, rsp.SubMsg)
		return
	}

	log.Printf("订单 %s 支付成功 \n", notification.OutTradeNo)

	client.ACKNotification(writer)
}
